package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IStatementService statementService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAudit.setCreateTime(new Date());
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {

        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateInstanceId(String instanceId, Long id) {
        carPackageAuditMapper.updateInstanceId(instanceId,id);
    }

    @Override
    @Transactional
    public InputStream getProcessImageByAuditId(Long id) {
        // 根据id查询审核对象,判断审核对象的状态
        CarPackageAudit audit = this.get(id);
        String instanceId = audit.getInstanceId(); // 审核对象关联的流程实例Id
        List<String> highLightActivities = null;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            // 获取流程实例对象
            // 如果处于审核中,高亮
            // 获取运行的任务
            highLightActivities = runtimeService.getActiveActivityIds(instanceId);  // 根据流程实例Id获取到目前活动节点
        } else {
            // 如果审核通过或者拒绝,不需要高亮
            highLightActivities = new ArrayList<>();
        }
        // 根据bpmnId查询 bpmnInfo对象,获取到流程定义的Id
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model,highLightActivities,Collections.EMPTY_LIST,"宋体","宋体","宋体");
    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        carPackageAuditMapper.changeAuditStatus(id,CarPackageAudit.STATUS_CANCEL);
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "撤销审核");
    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有审核中才能进行审批");
        }

        User user = ShiroUtils.getUser();
        if (!audit.getAuditorId().equals(user.getId())) {
            throw new BusinessException("非法操作");
        }
        if (CarPackageAudit.STATUS_PASS.equals(audit.getStatus())) {
            // 审批通过
            info = "["+ user.getUserName() +"]:"+"[同意]"+ info;
        } else {
            // 审批拒绝
            info = "["+ user.getUserName() +"]:"+"[拒绝]"+ info;
        }
        audit.setInfo(audit.getInfo()+"<br>"+ info);
        // 给任务添加流程变量
        Task currentTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);
        taskService.addComment(currentTask.getId(),audit.getInstanceId(),info);
        // 完成任务
        taskService.complete(currentTask.getId());
        //获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            // 审核通过
            if (nextTask != null) {
                // 财务审核
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                audit.setAuditTime(new Date());
            } else {

                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                audit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        } else {
            // 审核拒绝
            serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
    carPackageAuditMapper.updateByPrimaryKey(audit);
    }
}
